package com.example.qt.ptplatform.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.qt.ptplatform.entity.Seed;
import com.example.qt.ptplatform.entity.Torrent;
import com.example.qt.ptplatform.mapper.SeedMapper;
import com.example.qt.ptplatform.mapper.TorrentMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class TorrentStatusService {

    private final TorrentMapper torrentMapper;
    private final SeedMapper seedMapper;
    private final TrackerClientService trackerClientService;

    /**
     * 每 10s 更新一次所有种子的做种人数
     */
    @Scheduled(cron = "0/10 * * * * ?")
    @Transactional
    public void updateSeedersCount() {
        log.info("开始更新种子做种人数...");

        List<Torrent> torrents = torrentMapper.selectList(null);

        for (Torrent torrent : torrents) {
            int seeders = trackerClientService.getSeedersCount(torrent.getInfoHash());
            torrent.setSeeders(seeders);
            if(seeders == 0){
                LambdaQueryWrapper<Seed> wrapper = Wrappers.lambdaQuery();
                wrapper.eq(Seed::getTorrentId, torrent.getInfoHash());
                Seed seed = seedMapper.selectOne(wrapper);
                if(seed != null){
                    seed.setEndTime(LocalDateTime.now());
                    seedMapper.updateById(seed);
                }
            }
            torrentMapper.updateById(torrent);
            log.debug("更新种子 {} 的做种人数为: {}", torrent.getTorrentId(), seeders);
        }

        log.info("种子做种人数更新完成");
    }

}